<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<style>
		#cas{
			display: block;
			border:1px solid;
			margin:auto;
			background-color: #000;
		}
	</style>
	<script>
		window.onload = function(){
			canvas = document.getElementById("cas");
			context = canvas.getContext('2d');
			spritesheet = new Image();
			spritesheet.src = "image/explosion.png";
			var runnerCells = [
				{x:0 , y:0 , w:66 , h:64},
				{x:64 , y:0 , w:68 , h:64},
				{x:128 , y:0 , w:67 , h:64},
				{x:194 , y:0 , w:61 , h:64},
				{x:254 , y:0 , w:62 , h:64},
				{x:317 , y:0 , w:67 , h:64},
				{x:380 , y:0 , w:59 , h:64},
				{x:445 , y:0 , w:61 , h:64},
				{x:510 , y:0 , w:67 , h:64},
				{x:574 , y:0 , w:69 , h:64},
				{x:640 , y:0 , w:67 , h:64},
				{x:705 , y:0 , w:65 , h:64},
				{x:765 , y:0 , w:67 , h:64},
				{x:830 , y:0 , w:67 , h:64},
			]
			var sprite = new Sprite("runner" , new SpriteSheetPainter(runnerCells));
			sprite.left = "200";
			sprite.top = "50";
			var startTime = 0;
			startAnimate()

			function startAnimate(){
				startTime = +new Date();
				animate();
			}

			function animate(){
				context.clearRect(0,0,canvas.width,canvas.height);
				var nowTime = +new Date();
				if(nowTime - startTime > 40){
					sprite.painter.advance();
					startTime = nowTime;
				}
				sprite.paint();
				requestAnimationFrame(animate);
			}
		}

		//精灵类
		var Sprite = function(name , painter , behaviors){
			if(name !== undefined) this.name = name;
			if(painter !== undefined) this.painter = painter;
			this.top = 0;
			this.left = 0;
			this.width = 0;
			this.height = 0;
			this.velocityX = 0;
			this.velocityY = 0;
			this.visible = true;
			this.animating = false;
			this.behaviors = behaviors || [];
		}
		Sprite.prototype = {
			paint:function(){
				if(this.painter !== undefined && this.visible){
					this.painter.paint(this)
				}
			},
			update:function(time){
				for(var i=0;i<this.behaviors.length;i++){
					this.behaviors[i].execute(this,time);
				}
			}
		}

		// 精灵表绘制器
		var SpriteSheetPainter = function(cells){
			this.cells = cells || [];
			this.cellIndex = 0;
		}
		SpriteSheetPainter.prototype = {
			advance:function(){
				if(this.cellIndex === this.cells.length-1){
					this.cellIndex = 0;
				}
				else this.cellIndex++;
			},
			paint:function(sprite){
				var cell = this.cells[this.cellIndex];
				context.drawImage(spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left , sprite.top , cell.w , cell.h);
			}
		}
	</script>
	<title>精灵表测试</title>
</head>
<body>
	<div >
		<canvas id='cas' width="1000" height="500">浏览器不支持canvas</canvas>
	</div>
</body>
</html>